<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>王者荣耀英雄列表</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }

        .container {
            width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            text-align: center;
            margin-bottom: 20px;
        }

        .header img {
            height: 60px;
        }

        .filter-buttons {
            display: flex;
            justify-content: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .filter-btn {
            padding: 8px 15px;
            margin: 0 5px 10px;
            background-color: #fff;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .filter-btn:hover,
        .filter-btn.active {
            background-color: #f3c258;
            color: #fff;
            border-color: #f3c258;
        }

        .hero-list {
            display: grid;
            grid-template-columns: repeat(6, 1fr);
            gap: 15px;
        }

        .hero-item {
            background-color: #fff;
            border-radius: 5px;
            overflow: hidden;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s;
            text-align: center;
        }

        .hero-item:hover {
            transform: translateY(-5px);
        }

        .hero-img {
            width: 100%;
            height: auto;
            display: block;
        }

        .hero-name {
            padding: 10px;
            font-size: 14px;
            color: #333;
        }

        .hero-occupation {
            padding: 0 10px 10px;
            font-size: 12px;
            color: #999;
        }

        .loading {
            text-align: center;
            padding: 20px;
            font-size: 16px;
            color: #666;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="header">
            <img src="https://game.gtimg.cn/images/yxzj/web201706/images/logo.png" alt="王者荣耀">
        </div>

        <div class="filter-buttons">
            <button class="filter-btn active" data-occupation="all">全部</button>
            <button class="filter-btn" data-occupation="战士">战士</button>
            <button class="filter-btn" data-occupation="法师">法师</button>
            <button class="filter-btn" data-occupation="坦克">坦克</button>
            <button class="filter-btn" data-occupation="刺客">刺客</button>
            <button class="filter-btn" data-occupation="射手">射手</button>
            <button class="filter-btn" data-occupation="辅助">辅助</button>
        </div>

        <div class="hero-list" id="heroList">
            <div class="loading">加载中...</div>
        </div>
    </div>

    <script>
        // 封装的数据请求函数（合并后的版本）
        async function fetchData(url) {
            try {
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const data = await response.text();

                console.log("原始数据:", data); // 调试用

                // 更健壮的数据处理
                let jsonData;
                try {
                    // 尝试多种可能的JSONP格式
                    jsonData = data.replace(/^[a-zA-Z_$][0-9a-zA-Z_$]*\(/, '').replace(/\);?$/, '');
                    const parsedData = JSON.parse(jsonData);

                    if (!parsedData || !parsedData.data) {
                        throw new Error("无效的数据结构");
                    }

                    const filteredObj = parsedData.data.map(item => ({
                        title: item.title || '未知英雄',
                        occupation: item.occupation || '未知职业',
                        heroImg: item.heroimg || ''
                    }));

                    return {
                        data: filteredObj.slice(1)
                    };
                } catch (parseError) {
                    console.error("数据解析错误:", parseError);
                    throw new Error("数据解析失败");
                }
            } catch (error) {
                console.error('请求出错:', error);
                return {
                    error: error.message,
                    data: []
                };
            }
        }

        // 渲染英雄列表
        function renderHeroList(heroes, filter = 'all') {
            const heroListElement = document.getElementById('heroList');

            if (heroes.length === 0) {
                heroListElement.innerHTML = '<div class="loading">暂无数据</div>';
                return;
            }

            // 根据筛选条件过滤英雄
            const filteredHeroes = filter === 'all'
                ? heroes
                : heroes.filter(hero => hero.occupation.includes(filter));

            // 生成HTML
            const html = filteredHeroes.map(hero => {
                const heroName = hero.title.replace('故事站-英雄列表-', '');
                return `
                    <div class="hero-item">
                        <img src="${hero.heroImg}" alt="${heroName}" class="hero-img">
                        <div class="hero-name">${heroName}</div>
                        <div class="hero-occupation">${hero.occupation}</div>
                    </div>
                `;
            }).join('');

            heroListElement.innerHTML = html;
        }

        // 初始化页面（合并后的版本）
        async function init() {
            const url = 'https://pvp.qq.com/webplat/info/news_version3/15592/18024/23901/24397/24398/m17330/list_1.shtml?callback=createHeroList';

            try {
                const res = await fetchData(url);
                console.log(res, 'res');

                if (res.error) {
                    document.getElementById('heroList').innerHTML = `
                        <div class="loading">
                            数据加载失败: ${res.error}<br>
                            请刷新重试或检查控制台
                        </div>
                    `;
                    return;
                }

                if (res.data && res.data.length > 0) {
                    renderHeroList(res.data);

                    // 添加筛选按钮事件监听（这部分是从第一个init函数中保留的）
                    const filterButtons = document.querySelectorAll('.filter-btn');
                    filterButtons.forEach(button => {
                        button.addEventListener('click', () => {
                            // 更新按钮active状态
                            filterButtons.forEach(btn => btn.classList.remove('active'));
                            button.classList.add('active');

                            // 根据筛选条件重新渲染
                            const occupation = button.dataset.occupation;
                            renderHeroList(res.data, occupation);
                        });
                    });

                } else {
                    document.getElementById('heroList').innerHTML = `
                        <div class="loading">
                            获取到空数据，可能是接口已变更<br>
                            请检查API地址是否正确
                        </div>
                    `;
                }
            } catch (error) {
                console.error('初始化错误:', error);
                document.getElementById('heroList').innerHTML = `
                    <div class="loading">
                        发生未捕获的错误: ${error.message}<br>
                        请查看控制台获取详细信息
                    </div>
                `;
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>

</html>